// pages/activity/list.js
const eventApi = require('../../api/event');

Page({
  data: {
    events: [],
    sportTypes: [],
    activeType: '',
    keyword: '',
    page: 1,
    pageSize: 20,
    loading: false,
    hasMore: true,
    
    // 筛选相关
    showFilterModal: false,
    cities: ['北京', '上海', '广州', '深圳', '杭州', '成都'],
    selectedCity: '',
    feeFilter: 'all'
  },

  onLoad(options) {
    // 从URL参数获取关键词
    if (options.keyword) {
      this.setData({ keyword: options.keyword });
    }
    
    this.loadSportTypes();
    this.loadEvents();
  },

  /**
   * 加载运动类型
   */
  loadSportTypes() {
    eventApi.getSportTypes()
      .then(data => {
        this.setData({
          sportTypes: data || []
        });
      })
      .catch(err => {
        console.error('加载运动类型失败:', err);
      });
  },

  /**
   * 加载活动列表
   */
  loadEvents(reset = false) {
    if (this.data.loading) return;
    if (!reset && !this.data.hasMore) return;

    const page = reset ? 1 : this.data.page;

    this.setData({ loading: true });

    const params = {
      page,
      page_size: this.data.pageSize,
      sport_type_id: this.data.activeType || undefined,
      keyword: this.data.keyword || undefined,
      city: this.data.selectedCity || undefined
    };

    // 费用筛选
    if (this.data.feeFilter === 'free') {
      params.fee = 0;
    } else if (this.data.feeFilter === 'paid') {
      params.min_fee = 0.01;
    }

    eventApi.getEventList(params)
      .then(data => {
        const newEvents = data.items.map(item => {
          // 格式化时间
          item.start_time_formatted = this.formatDateTime(item.start_time);
          // 计算报名率
          item.signup_rate = item.max_participants > 0 
            ? Math.round((item.current_participants / item.max_participants) * 100)
            : 0;
          // 状态文本
          item.status_text = this.getStatusText(item.status);
          return item;
        });

        this.setData({
          events: reset ? newEvents : [...this.data.events, ...newEvents],
          page: page + 1,
          hasMore: newEvents.length >= this.data.pageSize,
          loading: false
        });
      })
      .catch(err => {
        console.error('加载活动列表失败:', err);
        this.setData({ loading: false });
      });
  },

  /**
   * 选择运动类型
   */
  selectType(e) {
    const { id } = e.currentTarget.dataset;
    this.setData({ 
      activeType: id,
      page: 1,
      hasMore: true
    });
    this.loadEvents(true);
  },

  /**
   * 搜索
   */
  onSearch(e) {
    const keyword = e.detail.value.trim();
    this.setData({ 
      keyword,
      page: 1,
      hasMore: true
    });
    this.loadEvents(true);
  },

  /**
   * 显示筛选弹窗
   */
  showFilter() {
    this.setData({ showFilterModal: true });
  },

  /**
   * 隐藏筛选弹窗
   */
  hideFilter() {
    this.setData({ showFilterModal: false });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {},

  /**
   * 选择城市
   */
  selectCity(e) {
    const { city } = e.currentTarget.dataset;
    this.setData({ selectedCity: city });
  },

  /**
   * 选择费用类型
   */
  selectFee(e) {
    const { fee } = e.currentTarget.dataset;
    this.setData({ feeFilter: fee });
  },

  /**
   * 重置筛选
   */
  resetFilter() {
    this.setData({
      selectedCity: '',
      feeFilter: 'all'
    });
  },

  /**
   * 应用筛选
   */
  applyFilter() {
    this.setData({ 
      showFilterModal: false,
      page: 1,
      hasMore: true
    });
    this.loadEvents(true);
  },

  /**
   * 加载更多
   */
  loadMore() {
    this.loadEvents(false);
  },

  /**
   * 导航到详情页
   */
  navigateToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/activity/detail?id=${id}`
    });
  },

  /**
   * 导航到创建页
   */
  navigateToCreate() {
    const app = getApp();
    app.checkLogin().then(() => {
      wx.navigateTo({
        url: '/pages/activity/create'
      });
    }).catch(() => {
      // 用户取消登录
    });
  },

  /**
   * 格式化日期时间
   */
  formatDateTime(dateTimeStr) {
    const date = new Date(dateTimeStr);
    const now = new Date();
    const diff = date - now;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;

    if (days === 0) {
      return `今天 ${timeStr}`;
    } else if (days === 1) {
      return `明天 ${timeStr}`;
    } else if (days === 2) {
      return `后天 ${timeStr}`;
    } else {
      return `${month}月${day}日 ${timeStr}`;
    }
  },

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    const statusMap = {
      'draft': '草稿',
      'published': '进行中',
      'cancelled': '已取消',
      'completed': '已结束'
    };
    return statusMap[status] || status;
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({ page: 1, hasMore: true });
    this.loadEvents(true);
    wx.stopPullDownRefresh();
  },

  /**
   * 分享
   */
  onShareAppMessage() {
    return {
      title: '发现精彩运动活动',
      path: '/pages/activity/list'
    };
  }
});

